package com.fits.gateway.api.filters;

import cn.hutool.core.util.StrUtil;
import cn.hutool.json.JSONUtil;
import com.fits.gateway.api.contsants.AuthConstants;
import com.fits.starter.common.security.LoginUserDTO;
import com.nimbusds.jwt.SignedJWT;
import org.springframework.cloud.gateway.filter.GatewayFilterChain;
import org.springframework.cloud.gateway.filter.GlobalFilter;
import org.springframework.core.annotation.Order;
import org.springframework.http.server.reactive.ServerHttpRequest;
import org.springframework.stereotype.Component;
import org.springframework.web.server.ServerWebExchange;
import reactor.core.publisher.Mono;

import java.text.ParseException;

/**
 * 网关过滤器
 *
 * @author lzy
 * @since 11:17 2024/7/4
 */
@Order(0)
@Component
public class AuthGlobalFilterConfig implements GlobalFilter {
    @Override
    public Mono<Void> filter(ServerWebExchange exchange, GatewayFilterChain chain) {
        String bearerToken = exchange.getRequest().getHeaders().getFirst(AuthConstants.JWT_TOKEN_HEADER);
        //没有token直接放行
        if (StrUtil.isBlank(bearerToken)) {
            return chain.filter(exchange);
        }
        //去除token前缀
        String token = bearerToken.replace(AuthConstants.JWT_TOKEN_PREFIX, "");
        //解析jwt token为用户信息
        String user = "{}";
        try {
            SignedJWT jwt = SignedJWT.parse(token);
            user = jwt.getPayload().toString();
            ServerHttpRequest request = exchange.getRequest().mutate()
                    .header(AuthConstants.USER_TOKEN_HEADER, user)
                    .build();
            exchange = exchange.mutate().request(request).build();
        } catch (ParseException e) {
            throw new RuntimeException("token校验错误");
        }
        //todo 校验权限
        LoginUserDTO userDTO = JSONUtil.toBean(user, LoginUserDTO.class);
        return chain.filter(exchange);
    }
}
